var app = getApp()
var temp = []
var serviceId = "0000ffe0-0000-1000-8000-00805f9b34fb"
var characteristicId = "0000ffe1-0000-1000-8000-00805f9b34fb"
var searchCardResult = false
var selectCardResult = false
var index = 0
var cardInfoArray = new Array()   
var util = require("../../utils/util.js");   
var message = ''
var analyCardTimer              

Page({
  data: {
    isbluetoothready: false,
    defaultSize: 'default',
    primarySize: 'default',
    warnSize: 'default',
    disabled: false,
    plain: false,
    loading: false,
    searchingstatus: false,
    receivedata: '',
    onreceiving: false,
    // devices:[]
    str: ""
  },
  onLoad: function () {
    // var str = "A13";
    // // var code = str.charCodeAt();
    // console.log(str.length)
    // console.log(str.charAt(0))
    // wx.showToast({
    //     title: '连接成功',
    //     icon: 'success',
    //     duration: 2000
    // })
    // let buffer = new ArrayBuffer(16)
    // let dataView = new DataView(buffer)
    // dataView.setUint8(1, 6)
    //console.log(dataView.getUint8(1))
  },
  switchBlueTooth: function () {
    var that = this

    that.setData({
      isbluetoothready: !that.data.isbluetoothready,
    })

    if (that.data.isbluetoothready) {
      wx.openBluetoothAdapter({
        success: function (res) {
          console.log("初始化蓝牙适配器成功")
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log("蓝牙适配器状态变化", res)
            that.setData({
              isbluetoothready: res.available,
              searchingstatus: res.discovering
            })
          })
          wx.onBluetoothDeviceFound(function (devices) {
            console.log(devices)
            console.log(devices.devices[0])
            if (!devices.devices[0].name) {
              return
            } else {
              temp.push(devices.devices[0])
              that.setData({
                devices: temp
              })
              console.log('发现新蓝牙设备')
              console.log('设备id' + devices.deviceId)
              console.log('设备name' + devices.name)
              wx.stopBluetoothDevicesDiscovery({
                success: function (res) {
                  console.log("停止蓝牙搜索")
                  console.log(res)
                }
              })
            }
          })
          //接收数据
          wx.onBLECharacteristicValueChange(function (characteristic) {
            // console.log('characteristic value comed:')
            let buffer = characteristic.value
            let dataView = new DataView(buffer)
            var intArray = new Uint8Array(buffer)//将arraybuffer转换为array
            // console.log('接收数据数组:', intArray)
            if (!searchCardResult && searchCardIsOk(intArray)) {//寻卡成功
              message += '寻卡成功'
              searchCardResult = true
              wx.writeBLECharacteristicValue({//选卡
                deviceId: that.data.connectedDeviceId,
                serviceId: serviceId,
                characteristicId: characteristicId,
                value: util.stringToArrayBuffer('aaaaaa96690003200221'),
                success: function (res) {
                  console.log(res)
                  console.log('writeBLECharacteristicValue success 2', res.errMsg)

                },
              })
            } else if (searchCardResult && !selectCardResult) {
              if (selectCardIsOk(intArray)) {//选卡成功
                message = +'---选卡成功'
                selectCardResult = true
                wx.writeBLECharacteristicValue({//读卡
                  deviceId: that.data.connectedDeviceId,
                  serviceId: serviceId,
                  characteristicId: characteristicId,
                  //value: util.stringToArrayBuffer('aaaaaa96690003301023'),   //读文字+照片+指纹信息，小程序无法解析照片，故显示都无照片信息
                  value: util.stringToArrayBuffer('aaaaaa96690003300132'),   //读文字+照片信息，小程序无法解析照片，故显示都无照片信息
                  success: function (res) {
                    console.log(res)
                    console.log('writeBLECharacteristicValue success 3', res.errMsg)
                  }
                })
              } else {
                startSearchCard(that);//寻卡
              }
            } else if (searchCardResult && selectCardResult) {
              for (var i = 0; i < intArray.byteLength; i++) {
                cardInfoArray[index] = intArray[i]
                index++//二代证 1297 三代证2321
              }
              clearTimeout(analyCardTimer)
              //if ((cardInfoArray.length == 2321) || (cardInfoArray.length == 1297)){
              if ((cardInfoArray.length == 2321) || (cardInfoArray.length == 1295)){
                analyCardTimer = setTimeout(function(){
                // message = '读卡成功' + cardInfoArray.length
                readCardIsOk(cardInfoArray)                  
                  updateInfo(that)
                },500)                
              }
             
            }else{
              startSearchCard(that);//寻卡
            }


            // console.log("本次接收字节长度:" + dataView.byteLength)
            var str = ""
            for (var i = 0; i < dataView.byteLength; i++) {
              // console.log((dataView.getUint8(i)))
              // str += String.fromCharCode(dataView.getUint8(i))
              var temp = (dataView.getUint8(i)).toString(16)
              var len = temp.length
              while (len < 2) {
                temp = '0' + temp//补位
                len++
              }
              // str = (dataView.getUint8(i)).toString(16)
              str += temp
            }

            // console.log("接收字节长度:" + str.length)
            // console.log(that.data.str)
            // str=getNowFormatDate()+"收到数据:"+str;
            // that.setData({
            //   receivedata: message,
            //   onreceiving: true
            // })


          })
        },
        fail: function (res) {
          console.log("初始化蓝牙适配器失败")
          wx.showModal({
            title: '提示',
            content: '请检查手机蓝牙是否打开',
            success: function (res) {
              that.setData({
                isbluetoothready: false,
                searchingstatus: false
              })
            }
          })
        }
      })
    } else {
      temp = []
      //先关闭设备连接
      wx.closeBLEConnection({
        deviceId: that.data.connectedDeviceId,
        complete: function (res) {
          console.log(res)
          that.setData({
            deviceconnected: false,
            connectedDeviceId: ""
          })
        }
      })
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log(res)
          that.setData({
            isbluetoothready: false,
            deviceconnected: false,
            devices: [],
            searchingstatus: false,
            receivedata: ''
          })
        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: '请检查手机蓝牙是否打开',
            success: function (res) {
              that.setData({
                isbluetoothready: false
              })
            }
          })
        }
      })
    }
  },
  searchbluetooth: function () {
    temp = []
    var that = this
    if (!that.data.searchingstatus) {
      var that = this
      wx.startBluetoothDevicesDiscovery({
        // services: [''],//指定services搜索 0000ffe0-0000-1000-8000-00805f9b34fb
        success: function (res) {
          console.log("开始搜索附近蓝牙设备")
          console.log(res)
          that.setData({
            searchingstatus: !that.data.searchingstatus
          })
        },
        fail: function(res){
          console.log("开始搜索附近蓝牙设备失败")
          console.log(res)
        }
      })
    } else {
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log("停止蓝牙搜索")
          console.log(res)
        }
      })
    }
  },
  connectTO: function (e) {
    var that = this

    if (that.data.deviceconnected) {
      wx.notifyBLECharacteristicValueChanged({
        state: false, // 停用notify 功能
        deviceId: that.data.connectedDeviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        success: function (res) {
          console.log("停用notify 功能")
        }
      })
      wx.closeBLEConnection({
        deviceId: e.currentTarget.id,
        complete: function (res) {
          console.log("断开设备")
          console.log(res)
          that.setData({
            deviceconnected: false,
            connectedDeviceId: "",
            receivedata: ""
          })
        }
      })
    } else {
      wx.showLoading({
        title: '连接蓝牙设备中...',
      })
      wx.createBLEConnection({
        deviceId: e.currentTarget.id,
        success: function (res) {
          wx.getBLEDeviceServices({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
            deviceId: e.currentTarget.id,
            success: function (res) {
			//下面两行，Android测试不行的时候注释测试下，Android比较复杂。
             serviceId = res.services[res.services.length-3].uuid;//苹果端可用 安卓端不可用，如果安卓读取失败，可以注释掉这行试试
             console.log('device services:', res)//如果安卓读取失败，可以注释掉这行试试
              setTimeout(function () {
                wx.getBLEDeviceCharacteristics({
                  deviceId: e.currentTarget.id,
                  serviceId: serviceId,
                  success: function (res) {
                    characteristicId = res.characteristics[0].uuid;
                    console.log("设备charater获取成功", res)
                    wx.notifyBLECharacteristicValueChanged({
                      state: true, // 启用 notify 功能
                      deviceId: that.data.connectedDeviceId,
                      serviceId: serviceId,
                      characteristicId: characteristicId,
                      success: function (res) {
                        console.log("启用notify")
                      },
                      fail: function (res) {
                        console.log("启用notify失败", res)
                      },
                    })
                  },
                  fail: function (res) {
                    console.log("设备charater获取失败", res)
                  },
                })
              }, 0)
            }
          })

          wx.hideLoading()
          wx.showToast({
            title: '连接成功',
            icon: 'success',
            duration: 1000
          })
          console.log("连接设备成功")
          console.log(res)
          that.setData({
            deviceconnected: true,
            connectedDeviceId: e.currentTarget.id
          })
        },
        fail: function (res) {
          wx.hideLoading()
          wx.showToast({
            title: '连接设备失败',
            icon: 'success',
            duration: 1000
          })
          console.log("连接设备失败")
          console.log(res)
          that.setData({
            connected: false
          })
        }
      })
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log("停止蓝牙搜索")
          console.log(res)
        }
      })
    }
  },
  formSubmit: function (e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value.senddata)
    // var senddata = e.detail.value.senddata;
    var that = this

    // this.setData({
    //   sengMessage: e.detail.value.senddata,
    // })


    // console.log(that.data.connectedDeviceId)
    console.log(serviceId)
    console.log(characteristicId)
    startSearchCard(that);//寻卡
  },
  clearData: function () {
    console.log('form发生了reset事件')
    this.setData({
      receivedata: "",
    })
  }
})



function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
  return currentdate;
}

//unicode为1个接收数据，串口收到的字符编码放在该数组中  
function UnicodeToUtf8(unicode) {
  var uchar;
  var utf8str = "";
  var i;

  for (i = 0; i < unicode.length; i += 2) {
    uchar = (unicode[i] << 8) | unicode[i + 1];               //UNICODE为2字节编码，一次读入2个字节  
    utf8str = utf8str + String.fromCharCode(uchar);    //使用String.fromCharCode强制转换  
  }
  return utf8str;
}


function Utf8ToUnicode(strUtf8) {
  var i, j;
  var uCode;
  var temp = new Array();

  for (i = 0, j = 0; i < strUtf8.length; i++) {
    uCode = strUtf8.charCodeAt(i);
    if (uCode < 0x100) {                 //ASCII字符  
      temp[j++] = 0x00;
      temp[j++] = uCode;
    } else if (uCode < 0x10000) {
      temp[j++] = (uCode >> 8) & 0xff;
      temp[j++] = uCode & 0xff;
    } else if (uCode < 0x1000000) {
      temp[j++] = (uCode >> 16) & 0xff;
      temp[j++] = (uCode >> 8) & 0xff;
      temp[j++] = uCode & 0xff;
    } else if (uCode < 0x100000000) {
      temp[j++] = (uCode >> 24) & 0xff;
      temp[j++] = (uCode >> 16) & 0xff;
      temp[j++] = (uCode >> 8) & 0xff;
      temp[j++] = uCode & 0xff;
    } else {
      break;
    }
  }
  temp.length = j;
  return temp;
}
//寻卡
function startSearchCard(that) {
  console.log('startSearchCard')
  searchCardResult = false
  selectCardResult = false
  message = ''
  index = 0 
  wx.writeBLECharacteristicValue({
    deviceId: that.data.connectedDeviceId,
    serviceId: serviceId,
    characteristicId: characteristicId,
    value: util.stringToArrayBuffer('aaaaaa96690003200122'),
    success: function (res) {
      console.log(res)
      console.log('writeBLECharacteristicValue success 1', res.errMsg)
    }, fail: function (res) {
      console.log("writeBLECharacteristicValue fail", res)
    },
  })
}
//寻卡结果分析
function searchCardIsOk(result) {
  var SW1 = result[7];
  var SW2 = result[8];
  var SW3 = result[9];

  if ((0x0 != SW1) || (0x0 != SW2) || (0x9F) != SW3) {
    return false;
  }

  return true;
}
//选卡结果分析
function selectCardIsOk(result) {
  console.log('选卡解析:', result)
  var SW1 = result[7];
  var SW2 = result[8];
  var SW3 = result[9];

  if ((0x0 != SW1) || (0x0 != SW2) || (0x90) != SW3) {
    return false;
  }
  console.log('选卡成功')
  return true;
}
//读卡结果分析
function readCardIsOk(_i_bys_resp){
  console.log('读卡解析:', _i_bys_resp)
  var SW1 = _i_bys_resp[7];
  var SW2 = _i_bys_resp[8];
  var SW3 = _i_bys_resp[9];

  if ((0x0 != SW1) || (0x0 != SW2) || ((0x90) != SW3) )
  {
    return false;
  }

  if (_i_bys_resp.length < 1024) {
    return false;
  }

  ///////////////////////////////////////////////////
  //
  var i = 0;
  var j = 0;
  var iOffset = 0;

  var bysName = new Array(30);
  var bysSexCode = new Array(2);
  var bysNationCode = new Array(4);
  var bysBirth = new Array(16);
  var bysAddr = new Array(70);
  var bysIdCode = new Array(36);
  var bysIssue = new Array(30);
  var bysBeginDate = new Array(16);
  var bysEndDate = new Array(16);

  var strName = '';
  var strSex = '';
  var strNation = '';
  var strBirth = null;
  var strAddr = null;
  var strIdCode = null;
  var strIssue = null;
  var strBeginDate = null;
  var strEndDate = null;

  var iTextSize = 0;
  var iPhotoSize = 0;
  var iFingerSize = 0;

  iTextSize = _i_bys_resp[10] << 8 + _i_bys_resp[11];
  iPhotoSize = _i_bys_resp[12] << 8 + _i_bys_resp[13];
  iFingerSize = _i_bys_resp[14] << 8 + _i_bys_resp[15];

  ///////////////////////////////////////////////////
  //截取数据

  //iOffset = 16;
  iOffset = 14;

  //截取姓名
  j = 0;
  for (i = iOffset; i < (iOffset + 30); i++) {
    bysName[j] = _i_bys_resp[i];
    j++;
  }
  try {
    strName = util.uint8ArrayToStr(bysName)
    console.log('姓名:',strName)
    message = '姓名:'+strName
  }
  catch (Exception) {
  }
  iOffset += 30;

  //截取性别
  j = 0;
  for (i = iOffset; i < (iOffset + 2); i++) {
    bysSexCode[j] = _i_bys_resp[i];
    j++;
  }
  var strSexCode= null;
  try {
    strSexCode = util.uint8ArrayToStr(bysSexCode);
    strSex = util.getSexFromCode(strSexCode);
    console.log('性别:', strSex)
    message += ',' + '性别:' + strSex
  }
  catch (Exception) {
  }
  iOffset += 2;

  //截取民族
  j = 0;
  for (i = iOffset; i < (iOffset + 4); i++) {
    bysNationCode[j] = _i_bys_resp[i];
    j++;
  }
  var strNationCode = null;
  try {
    strNationCode = util.uint8ArrayToStr(bysNationCode,);
    strNation = util.getNationFromCode(strNationCode);
    console.log('民族:', strNation)
    message += ',' + '民族:' + strNation
  }
  catch (Exception) {
  }
  iOffset += 4;

  //截取生日
  j = 0;
  for (i = iOffset; i < (iOffset + 16); i++) {
    bysBirth[j] = _i_bys_resp[i];
    j++;
  }
  try {
    strBirth = new String(bysBirth, "UTF-16LE");
  }
  catch (Exception) {
  }
  iOffset += 16;

  //截取地址
  j = 0;
  for (i = iOffset; i < (iOffset + 70); i++) {
    bysAddr[j] = _i_bys_resp[i];
    j++;
  }
  try {
    strAddr = util.uint8ArrayToStr(bysAddr);
    console.log('地址:', strAddr)
    message += ',' + '地址:' + strAddr
  }
  catch (Exception) {
  }
  iOffset += 70;

  //截取身份证号
  j = 0;
  for (i = iOffset; i < (iOffset + 36); i++) {
    bysIdCode[j] = _i_bys_resp[i];
    j++;
  }
  try {
    strIdCode = util.uint8ArrayToStr(bysIdCode);
    console.log('身份证号:', strIdCode)
    message += ',' + '身份证号:' + strIdCode
  }
  catch (Exception) {
  }
  iOffset += 36;

  //截取签发机关
  j = 0;
  for (i = iOffset; i < (iOffset + 30); i++) {
    bysIssue[j] = _i_bys_resp[i];
    j++;
  }
  try {
    strIssue = util.uint8ArrayToStr(bysIssue);
    console.log('签发机关:', strIssue)
    message += ',' + '签发机关:' + strIssue
  }
  catch (Exception) {
  }
  iOffset += 30;

  //截取有效期开始日期
  j = 0;
  for (i = iOffset; i < (iOffset + 16); i++) {
    bysBeginDate[j] = _i_bys_resp[i];
    j++;
  }
  try {
    strBeginDate = util.uint8ArrayToStr(bysBeginDate);
    console.log('有效期开始日期:', strBeginDate)
    message += ',' + '有效期开始日期:' + strBeginDate
  }
  catch (Exception) {
  }
  iOffset += 16;

  //截取有效期结束日期
  j = 0;
  for (i = iOffset; i < (iOffset + 16); i++) {
    bysEndDate[j] = _i_bys_resp[i];
    j++;
  }
  try {
    if (bysEndDate[0] >= '0' && bysEndDate[0] <= '9') {
      // strEndDate = new String(bysEndDate, "UTF-16LE");
    }
    else {
      // strEndDate = new String(bysEndDate, "UTF-16LE");
    }
    strEndDate = util.uint8ArrayToStr(bysEndDate)
    console.log('有效期结束日期:', strEndDate)
    message += ',' + '有效期开结束日期:' + strEndDate
  }
  catch (Exception) {
  }
  iOffset += 16;

  // //照片
  // var wlt = new byte[1024];
  // byte[] bmp = new byte[14 + 40 + 308 * 126];
  // for (i = 0; i < iPhotoSize; i++) {
  //   wlt[i] = _i_bys_resp[16 + iTextSize + i];
  // }
  // //int iResult = JniCall.hxgc_Wlt2Bmp(wlt, bmp, 0);
  // int iResult = DecodeWlt.hxgc_Wlt2Bmp(wlt, bmp, 708);
  // Bitmap bitmapIdPhoto = null;
  // if (iResult != -1) {
  //   bitmapIdPhoto = BitmapFactory.decodeByteArray(bmp, 0, bmp.length);
  // }

  ////////////////////////---显示数据---///////////////////////////
  // ShowStringInUI("姓名:" + strName + "\n");
  // ShowStringInUI("性别:" + strSex + "\n");
  // ShowStringInUI("民族:" + strNation + "\n");
  // ShowStringInUI("出生:" + strBirth + "\n");
  // ShowStringInUI("住址:" + strAddr + "\n");
  // ShowStringInUI("证号:" + strIdCode + "\n");
  // ShowStringInUI("签发:" + strIssue + "\n");
  // ShowStringInUI("期限:" + strBeginDate + "-" + strEndDate + "\n");
  // ShowStringInUI("\n");
  
  return true;
  
}
function updateInfo(that){
  that.setData({
    receivedata: message,
    // receivedata: that.data.receivedata + "\n" + that.data.str,
    onreceiving: true
  })
}
